package com.apes.scm.masterdata.finance.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.finance.model.Bank;
import com.apes.scm.masterdata.finance.repository.BankRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 功能：
 *
 * @Auther: bieb
 * @Date: 2018-8-31 14:31:49
 */
@Service("bankService")
public class BankService extends DomainService {
    @Autowired
    BankRepository bankRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public Bank save(SimpleRequest request){
        Bank bank = request.getO(Bank.class);
        return bankRepository.saveAndFlush(bank);
    }

    /***
     * 功能：
     * @param request
     * @return
     */
    public Bank update(SimpleRequest request) {
        String id = request.get("id");
        Bank bank = request.getO(Bank.class);
        Bank tempBank = bankRepository.findOne(id);
        if (tempBank == null) throw new RuntimeException("银行【" + id + "】在系统中不存在。");
        if(tempBank.getVersion() != bank.getVersion()) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
        return bankRepository.saveAndFlush(bank);
    }

    /***
     * 功能： 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Bank bank = request.getO(Bank.class);
        Bank tempBank = bankRepository.findOne(id);
        if (tempBank == null) throw new RuntimeException("银行【"+ id +"】在系统中不存在。");
        if (bank.getVersion() != tempBank.getVersion()) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        bankRepository.delete(bank);
        return "删除成功";
    }

}
